﻿using Coder.Beer.Robot.Api.ApplicationModel;
using Coder.Beer.Robot.Api.Repository;
using Flurl;
using Flurl.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Mirai.Net.Api.Contract;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace Coder.Beer.Robot.Api.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class RobotListener : ControllerBase
    {
        private readonly BeerDbContext beerDbContext;

        public RobotListener(BeerDbContext beerDbContext)
        {
            this.beerDbContext = beerDbContext;
        }
        [HttpPost("confirmJoinGroup")]
        public async Task<IActionResult> ConfirmJoinGroupAsync([FromBody] MemberJoinRequestMessage message)
        {
            var fromUser = await beerDbContext.UserConnecteds.FirstOrDefaultAsync(x => x.QQ == message.FromId);
            if (fromUser == null)
            {
                //请添加QQ[594854469]为好友并向其发送“我要入群”
                //添加[594854469]并向其发送“入群”
                return BadRequest("添加[594854469]并向其发送“入群”");
            }
            else if (fromUser.BeerUsername == null)
            {
                return BadRequest("你还没有注册啤酒会");
            }
            else if (fromUser.GiteeHome == null)
            {
                return BadRequest("你还没有绑定码云主页");
            }
            else if (fromUser.GiteeToken?.AccessToken == null)
            {
                return BadRequest("你还没有授权码云权限");
            }
            else if (!fromUser.Stared)
            {
                return BadRequest("你还没有加星");
            }
            return Ok("欢迎入群");
        }


        [HttpPost("friendMessage")]
        public async Task<IActionResult> ReciveFriendMessageAsync([FromBody] FriendMessage message)
        {
            var fromUser = await beerDbContext.UserConnecteds.FirstOrDefaultAsync(x => x.QQ == message.Sender.Id);
            if (fromUser == null)
            {
                fromUser = new Repository.Model.UserConnected()
                {
                    QQ = message.Sender.Id
                };
                beerDbContext.UserConnecteds.Add(fromUser);
                await beerDbContext.SaveChangesAsync();
            }

            var firstPlainNode = message.MessageChain?.Cast<JsonElement>()?.FirstOrDefault(x => x.GetProperty("type").GetString() == "Plain");
            var messageContent = string.Empty;
            if (firstPlainNode.HasValue && firstPlainNode.Value.ValueKind != JsonValueKind.Undefined)
            {
                messageContent = firstPlainNode.Value.GetProperty("text").GetString()?.Trim() ?? "";
            }
            else
            {
                firstPlainNode = message.MessageChain?.Cast<JsonElement>()?.FirstOrDefault(x => x.GetProperty("type").GetString() == "Xml");
                var xml = firstPlainNode.Value.GetProperty("xml").GetString();
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(msg));
                var stringReader = new StringReader(xml);
                var xmlMsg = (msg)xmlSerializer.Deserialize(stringReader);
                messageContent = xmlMsg.url;
            }

            if (messageContent == "我要解绑码云")
            {
                fromUser.GiteeHome = null;
                fromUser.GiteeToken = null;
                await beerDbContext.SaveChangesAsync();
                return Ok("已解绑码云账号，发送任意字符开始重新绑定");
            }

            if (string.IsNullOrWhiteSpace(fromUser.BeerUsername))
            {
                if (messageContent.Contains("入群") || messageContent.Contains("加群"))
                {
                    return Ok("第 4/1 步，点击链接注册社区账号：http://www.coder.beer \n为方便新人学习，也为了让大家的智慧能沉淀下来\n我们正在建立 .Net 中文社区，在社区中的技术性提问，我们有问必答。\nQQ群中不处理技术相关提问。\n注册完成后，请[只]将用户名发送给我。");
                }
                var exists = await beerDbContext.UserConnecteds.AnyAsync(x => x.BeerUsername == messageContent);
                if (exists)
                {
                    return Ok("这个用户名已经被用过了，你是把别人的用户名发来忽悠我了吗？");
                }

                if (messageContent.Contains("/") || messageContent.Contains("\\") || messageContent.Contains("http:") || messageContent.Contains(" "))
                {
                    return Ok("发一个正确的给我");
                }

                try
                {
                    await ("http://www.coder.beer/user/" + messageContent).GetStringAsync();
                    fromUser.BeerUsername = messageContent;
                    await beerDbContext.SaveChangesAsync();
                    return Ok("好的，我这边记录下来了\n第 4/2 步，接下来请提供一下你的码云个人主页地址，比如：https://gitee.com/wzxinchen ，码云登录后可以从右上角下拉菜单中的个人主页拿到这个地址");
                }
                catch (FlurlHttpException ex)
                {
                    var responseMessage = await ex.GetResponseStringAsync();
                    if (responseMessage.Contains("未找到"))
                    {
                        return Ok("访问http://www.coder.beer/user/" + messageContent + "地址失败了，你提供的用户名不正确");
                    }
                    return Ok(responseMessage + "\n社区出现了问题，请联系QQ 1101385391，并将上述错误信息发给他");
                }

            }

            if (string.IsNullOrWhiteSpace(fromUser.GiteeHome))
            {
                try
                {
                    messageContent = messageContent.Split('?')[0];
                    var result = await messageContent.GetStringAsync();
                    if (result.Contains(messageContent) && result.Contains(messageContent))
                    {
                        fromUser.GiteeHome = messageContent;
                        await beerDbContext.SaveChangesAsync();

                        return Ok("好的，我这边记录下来了\n第 4/3 步，需要绑定您的码云账号给我，打开这个地址 https://gitee.com/oauth/authorize?client_id=52fbf65a494ad533a866c24b8f8612f14c25d3a571868b54ef6af6008ff65285&redirect_uri=http%3A%2F%2Frobot.coder.beer%2Fapi%2Fcallback%2Fgitee&response_type=code ，完成授权绑定");

                    }
                    else
                    {
                        return Ok("你提供的地址不是码云个人主页地址");
                    }
                }
                catch (FlurlHttpException ex)
                {
                    var responseMessage = await ex.GetResponseStringAsync();
                    if (responseMessage == null)
                    {
                        return Ok("你提供的地址打不开");
                    }
                    if (responseMessage.Contains("你所访问的页面不存在"))
                    {
                        return Ok("你提供的地址报404了");
                    }
                    return Ok(responseMessage + "\n码云挂了？请联系QQ 1101385391，并将上述错误信息发给他");
                }
            }

            if (fromUser.GiteeToken == null || fromUser.GiteeToken.AccessToken == null)
            {
                return Ok("快去绑定码云");
            }

            if (!fromUser.Stared)
            {
                var passed = false;
                if (messageContent.Contains("好了"))
                {
                    try
                    {
                        var response = await $"https://gitee.com/api/v5/user/starred/zion-sanctuary/programming-educational-games?access_token={fromUser.GiteeToken.AccessToken}".GetAsync();
                        if (response.StatusCode == 204)
                        {
                            fromUser.Stared = true;
                            passed = true;
                            await beerDbContext.SaveChangesAsync();
                            return Ok("好了，我没有权限拉你入群，你再次申请入群吧");
                        }
                    }
                    catch (FlurlHttpException e)
                    {
                    }
                }
                if (!passed)
                {
                    return Ok("第 4/4 步，接下来请去给码云项目 https://gitee.com/zion-sanctuary/programming-educational-games 点颗星，这个项目是我们的游戏项目的一部分，我们需要您的支持来宣传它。\n点了之后，请发送“好了”.");
                }
            }

            return Ok("test");
        }

        [HttpPost("confirmNewFriend")]
        public async Task<string> ConfirmNewFriendAsync([FromBody] MemberJoinRequestMessage message)
        {
            var fromUser = await beerDbContext.UserConnecteds.FirstOrDefaultAsync(x => x.QQ == message.FromId);
            if (fromUser == null)
            {
                fromUser = new Repository.Model.UserConnected()
                {
                    QQ = message.FromId
                };
                beerDbContext.UserConnecteds.Add(fromUser);
            }
            await beerDbContext.SaveChangesAsync();
            if (string.IsNullOrWhiteSpace(fromUser.BeerUsername))
            {
                _ = Task.Delay(8000).ContinueWith((task) =>
                  {
                      _ = NodeBBWatcher.SendMessageToUserAsync(message.FromId, "入群指南：\n第 4/1 步，点击链接注册社区账号：http://www.coder.beer \n为方便新人学习，也为了让大家的智慧能沉淀下来\n我们正在建立 .Net 中文社区，在社区中的技术性提问，我们有问必答。\nQQ群中不处理技术相关提问。\n注册完成后，请[只]将用户名发送给我。");
                  });
            }
            return string.Empty;
        }
    }
}
